package com.huan.pdf.utils;

import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * pdf工具类
 *
 * @author admin
 */
@Slf4j
public class PdfUtils {

    public static void mergePdf(HttpServletResponse response, String... pdfTemplates) throws IOException {
        // pdf合并
        PDFMergerUtility merger = new PDFMergerUtility();
        for (String pdfTemplate : pdfTemplates) {
            merger.addSource(htmlToInputStream(pdfTemplate));
        }
        merger.setDestinationStream(response.getOutputStream());
        merger.mergeDocuments(null);
    }

    /**
     * HTML → byte[] （内存）
     */
    private static ByteArrayInputStream htmlToInputStream(String html) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            PdfRendererBuilder builder = new PdfRendererBuilder();
            builder.useFont(() -> PdfUtils.class.getClassLoader().getResourceAsStream("fonts/simsun.ttf"), "SimSun");
            builder.withHtmlContent(html, null);
            builder.toStream(bos);
            builder.run();
            return new ByteArrayInputStream(bos.toByteArray());
        }
    }
}
